package com.autumn.platform.web.request.impl;

import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;

import net.sf.uadetector.ReadableUserAgent;
import net.sf.uadetector.UserAgentStringParser;
import net.sf.uadetector.service.UADetectorServiceFactory;

/* package */class UserAgentUtils {

    private static ConcurrentHashMap<String, ReadableUserAgent> cache = new ConcurrentHashMap<String, ReadableUserAgent>();

    private static UserAgentStringParser parser = UADetectorServiceFactory.getCachingAndUpdatingParser();

    public static String getDataVersion() {
        return parser.getDataVersion();
    }

    public static void shutdown() {
        parser.shutdown();
    }

    public static ReadableUserAgent getUserAgent(HttpServletRequest request) {
        return parseUserAgent(request.getHeader("User-Agent"));
    }

    public static ReadableUserAgent parseUserAgent(String userAgentString) {
        ReadableUserAgent result = cache.get(userAgentString);
        if (result == null) {
            result = parser.parse(userAgentString);
            cache.put(userAgentString, result);
        }
        return result;
    }
}
